package com.linser.gistools.utils;

import org.mozilla.universalchardet.UniversalDetector;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class DataOperation {

    /**
     *  getCharset 获取字符编码 UniversalDetector 目前不支持GBK但是 utf-8还是能识别出来的
     * @param filePath 文件路径
     * @return charset
     */
    public static String getCharset(String filePath) {
        String charset = "GBK";
        File file = new File(filePath);
        FileInputStream fis;
        try {
            fis = new FileInputStream(file);
            byte[] bytes = new byte[2048];
            int len;
            // 初始化 CharsetDetector
            UniversalDetector detector = new UniversalDetector(null);
            while ((len = fis.read(bytes)) != -1 && !detector.isDone()){

                // 将数据填充到 CharsetDetector
                detector.handleData(bytes, 0, len);
                // 完成数据填充
                detector.dataEnd();
                // 获取检测出来的字符集
                String encoding = detector.getDetectedCharset();
                if ("utf-8".equalsIgnoreCase(encoding)){
                    charset = "utf-8";
                    break;
                }
                // 释放资源
                detector.reset();
            }
            fis.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return charset;
    }
    public static String mapToString(Map<String, String> map) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            sb.append(entry.getKey()).append("=").append(entry.getValue()).append("\n");
        }
        return sb.toString();
    }
    public static Map<String, String> stringToMap(String str) {
        Map<String, String> map = new HashMap<>();
        String[] lines = str.split("\n");
        for (String line : lines) {
            int index = line.indexOf('=');
            if (index > 0) {
                // 截取第一个等号前的值
                String key = line.substring(0, index);

                // 截取第一个等号后面的值
                String value = line.substring(index + 1);
                map.put(key, value);
            }
        }
        return map;
    }

}
